##
## Hosted Game: Capture
## D1st0rt, SSCE Hyperspace
## License: MIT/X11
## Created: 2009-02-13
## Updated: 2009-05-12
##
## Anyone you kill joins your team. If you kill the leader of another team,
## their whole team joins yours. Leader of the last team standing wins.
##
import asss

chat = asss.get_interface(asss.I_CHAT)
game = asss.get_interface(asss.I_GAME)
hgcore = asss.get_interface(asss.I_HGCORE)
pd = asss.get_interface(asss.I_PLAYERDATA)
stats = asss.get_interface(asss.I_STATS)

class HG_Capture:
    iid = asss.I_HOSTEDGAME

    def OnPrepare(self, a, host, params):
        chat.SendArenaMessage(a, "New game of capture beginning! Anyone you kill joins your team.")
        chat.SendArenaMessage(a, "Leader of the last team standing wins!")
        a.hg_capture_teams.clear()
        return (1,)

    def OnStart(self, a, host):
        game.GivePrize(a, asss.PRIZE_WARP, 1)
        game.ShipReset(a)
        game.Lock(a, 0, 0, 0)
        game.LockArena(a, 0, 0, 0, 0)
        hgcore.EndInterval(a, asss.INTERVAL_RESET)
        def fill_teams(p):
            if p.arena == a:
                if p.freq in a.hg_capture_teams:
                    a.hg_capture_teams[p.freq].append(p.name)

        asss.for_each_player(fill_teams)
        return (1,)

    def OnGameOver(self, a, how):
        game.Unlock(a, 0)
        game.UnlockArena(a, 0, 0)
        if how == asss.HGR_NONE_REMAINING:
            chat.SendArenaMessage(a, "Game canceled, there is nobody left.")
        elif how == asss.HGR_NATURAL:
            if len(a.hg_capture_teams) > 0:
                (freq,team) = a.hg_capture_teams.popitem()
                leader = "unknown"
                if len(team) > 0:
                    leader = team[0]
                chat.SendArenaMessage(a, "Team %s was the last team standing! (Leader: %s)" % (freq, leader))

            #for some reason, scope issues came up when just defining mvpkills = 0
            data = {"mvp" : "unknown", "mvpkills" : 0}

            def capture_mvp(p,data):
                if p.arena == a:
                    kills = stats.GetStat(p, asss.STAT_KILLS, asss.INTERVAL_RESET)
                    if kills > data['mvpkills']:
                        data['mvpkills'] = kills
                        data['mvp'] = p.name

            asss.for_each_player(lambda p : capture_mvp(p,data))
            chat.SendArenaMessage(a, "%s is the MVP with %d kills!" % (data['mvp'], data['mvpkills']))

    def OnCleanup(self, a):
        a.hg_capture_teams.clear()

    def OnTeamCreate(self, a, team):
        a.hg_capture_teams[team.Freq] = []

    def OnTeamDestroy(self, a, team):
        if team.Freq in a.hg_capture_teams:
            del a.hg_capture_teams[team.Freq]

    def SizeOfTeamData(self):
        return 0

    def TeamInfoString(self, team, str):
        return str

def PlayerKill(a, killer, killed, bty, flags, pts, green):
    if killed.freq in a.hg_capture_teams:
        team = a.hg_capture_teams[killed.freq]
        if killed.name in team:
            team.remove(killed.name)
            if len(team) < 1:
                del a.hg_capture_teams[killed.freq]

    if killer.freq in a.hg_capture_teams:
        team = a.hg_capture_teams[killer.freq]
        team.append(killed.name)

    game.SetFreq(killed, killer.freq)
    return (pts, green)

def mm_attach(a):
    try:
        a.hg_capture_myint = asss.reg_interface(HG_Capture(), a)
        a.hg_capture_cb1 = asss.reg_callback(asss.CB_KILL, PlayerKill, a)
        a.hg_capture_teams = {}
    except:
        mm_detach(a)
        return

    if hgcore.AttachGame(a, asss.I_HOSTEDGAME, "hg_capture") == 0:
        mm_detach(a)
        raise Exception("Could not attach to HGCore")


def mm_detach(a):
    hgcore.DetachGame(a)
    for attr in ['myint', 'cb1', 'teams']:
        try: delattr(a, 'hg_capture_' + attr)
        except: pass
